<?php

namespace App\Http\Controllers;

use App\Http\Requests\RegisterRequest;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class UserController extends Controller
{
    //获取用户
    private function getUser(string $name)
    {
        $user = User::where('name', $name);
        foreach(['email','mobile'] as $field){
            // 用户可以使用name登录，也可以使用email,mobile登录
            $user->orWhere($field, $name);
        }
        return $user->first();
    }

    public function login(Request $request)
    {
        // 用户登录
        $user  = $this->getUser($request->input('name'));
        $request->validate([
            'name' => ['required',function($attr,$value,$fail) use ($user) {
                if(!$user){
                    $fail('账号不存在，请检查账号');
                }
            }],
            'password' => [
                'required',function($attr,$value,$fail) use ($user,$request) {
                    if(!$user || !Hash::check($request->input('password'), $user->password)){
                        $fail('密码错误，请重新输入密码');
                    }
                }
            ]
        ]);
        Auth::login($user); // 用户登录
        return ['data'=>$user,'msg' => '恭喜你，登录成功','code' => 0];
    }

    public function register(RegisterRequest $registerRequest,User $user)
    {
        // 用户注册
        $user->name = $registerRequest->input('name');
        $user->password = $registerRequest->input('password');
        $user->save();
        return ['data'=>$user,'msg' => '恭喜你，注册成功','code' => 0];
    }

    public function logout()
    {
        Auth::logout(); // 退出登录
        return ['code' => 0, 'msg' => '退出登录成功'];
    }
}
